﻿#include('/header.html', {title : '试卷列表'})
<style>
  .uploader-container {
    padding: 5px !important;
  }
</style>
<div class="es-wrap">
  <div id="content-container" class="container">
    #include('header.html')
    <div class="row">
      <div class="col-sm-3">
        <div class="sidenav locked js-sidenav" data-course-length="1">
          #include('sideMenu.html', {testpaper : 'active'})
        </div>
      </div>
      <div id="paper-content" class="col-sm-9">
        <div class="panel panel-default panel-col">
          <div class="panel-heading">
            <button @click="edit_(-1)" class="btn btn-info btn-sm pull-right mls">
              <span class="es-icon es-icon-anonymous-iconfont"></span>创建试卷
            </button>
            试卷管理
          </div>
          <div class="panel-body " id="quiz-table-container">
            <table class="table table-striped table-hover" id="quiz-table">
              <thead>
              <tr>
                <th>序号</th>
                <th>名称</th>
                <th>下载人数</th>
                <th>提交人数</th>
                <th>创建时间</th>
                <th>截止时间</th>
                <th>操作</th>
              </tr>
              </thead>
              <tbody>
              <tr v-if="papers.length<=0">
                <td colspan="7" class="empty">暂无试卷</td>
              </tr>
              <tr is="paper-li" v-for="(pp, index) in papers"
                  :paper="pp" :index="index" :key="pp.id"
                  :edit_="edit_" :delete_="delete_"></tr>
              </tbody>
            </table>
            <div v-if="page.totalPages > 1" class="text-center">
              <navigation :pages="page.totalPages" :current.sync="page.pageNum" @navpage="gotoPage"/>
            </div>
          </div>
        </div>

        <!--创建试卷的模态框-->
        <div class="modal fade" id="createNotice" data-backdrop="static">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button class="close" onclick="hideM(true)">&times;</button>
                <h4 class="modal-title">创建试卷</h4>
              </div>
              <div class="modal-body">
                <form class="form-horizontal">
                  <div class="row form-group">
                    <div class="col-sm-3 control-label">
                      <label for="name">试卷名称</label>
                    </div>
                    <div class="col-sm-8 controls">
                      <input id="name" class="form-control" v-model="paper.name" placeholder="如：期中考试试卷">
                    </div>
                  </div>
                  <div class="row form-group">
                    <div class="col-sm-3 control-label">
                      <label for="endTime">截止时间</label>
                    </div>
                    <div class="col-sm-8 controls">
                      <input ref="endTime" id="endTime" class="form-control">
                    </div>
                  </div>
                  <div class="row form-group">
                    <div class="col-sm-3 control-label">
                      <label for="intro">考试说明</label>
                    </div>
                    <div class="col-sm-8 controls">
                      <textarea cols="4" id="intro" class="form-control" v-model="paper.intro"></textarea>
                    </div>
                  </div>
                  <div class="col-sm-8 col-sm-offset-3" v-if="progress>=0">
                    <div class="progress progress-striped">
                      <div class="progress-bar progress-bar-success" :style="'width:' + progress + '%'">
                        <span>{{progress}}%</span>
                      </div>
                    </div>
                  </div>
                  <div class="row form-group">
                    <div class="col-sm-3 control-label">
                      <label>上传试卷</label>
                    </div>
                    <div class="col-sm-8">
                      <div ref="upload_paper" class="uploader-content">
                        <div class="uploader-container text-center"
                             v-html="paper.path!=null?'<font color=green>文件已保存！</font>' :'文件上传(支持word,pdf,txt)!'"></div>
                      </div>
                    </div>
                  </div>
                  <div v-show="paper.id>0" class="row form-group">
                    <div class="col-sm-3 control-label">
                      <label>上传答案</label>
                    </div>
                    <div class="col-sm-8">
                      <div ref="upload_result" class="uploader-content">
                        <div class="uploader-container text-center"
                             v-html="paper.result!=null?'<font color=green>文件已保存！</font>' :'文件上传(支持word,pdf,txt)!'"></div>
                      </div>
                    </div>
                  </div>
                </form>
                <input ref="file_in" type="file" class="hide" accept=".docx,.doc">
              </div>
              <div class="modal-footer">
                <button v-if="paper.id>0" @click="changePaper" class="btn btn-success"> 保 存</button>
                <button v-if="paper.id<=0" @click="createPaper" class="btn btn-info"> 创 建</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<template id="paper-li">
  <tr>
    <th>{{index+1}}</th>
    <td>{{paper.name | sub}}</td>
    <td>{{paper.downs}}</td>
    <td>{{paper.submits}}</td>
    <td>{{paper.time}}</td>
    <td>{{paper.endTime}}</td>
    <td class="dropdown">
      <button @click="edit_(index)" class="btn btn-success btn-xs">编辑</button>
        <button class="dropdown-toggle btn btn-danger btn-xs" data-toggle="dropdown">
          更多<i class="es-icon es-icon-arrowdropdown"></i>
        </button>
        <ul class="dropdown-menu">
          <li>
            <a href="javascript:" @click="down(paper.path)">
              <span class="glyphicon glyphicon-save"></span> 试卷下载
            </a>
          </li>
          <li>
            <a href="javascript:" @click="down(paper.result)">
              <span class="glyphicon glyphicon-save"></span> 答案下载
            </a>
          </li>
          <li>
            <a @click="delete_(index)" href="javascript:">
              <span class="es-icon es-icon-delete"></span> 删除
            </a>
          </li>
        </ul>
    </td>
  </tr>
</template>
<script>
  var paperVm = new Vue({
    el: '#paper-content',
    data: {
      progress: -1,
      kid: ${kid},
      papers: [],
      paper: {
        id: 0,
        path: null,
        result: null
      },
      page: {
        pageNum: 1,
        totalPages: 1,
        limit: 10
      },
      fileType: 'test_paper' // test_result
    },
    watch: {
      'page.pageNum': function (nv) {
        this.getPages();
      }
    },
    methods: {
      gotoPage: function(i){
        this.page.pageNum=i;
      },
      edit_: function (index) {
        if (index >= 0) this.paper = this.papers[index];
        if (this.paper.folder==null) this.paper.folder = uuid(7);
        openM();
      },
      delete_: function (index) {
        var self = this;
        layer.confirm('确定要删除？',{icon: 5, title: '提示'}, function (i) {
          var tgp = self.papers[index];
          $.post('/course/set/paper/${kid}/delete/' + tgp.id, function (data) {
            if (data.success) {
              self.papers.splice(index, 1);
              if (self.papers.length <= 0) self.page.pageNum--;
              self.getPages();
            }
          });
          layer.close(i);
        });
      },
      changePaper: function () {
        if (this.checkForm()) {
          var self = this;
          self.paper.endTime = self.$refs.endTime.value;
          $.post('/course/set/paper/${kid}/change', self.paper, function (data) {
            if (data.success) {
              $.extend(self.paper, data.payload);
              layer.msg('操作成功！', {icon: 6, time: 1200});
              hideM();
            }
          });
        }
      },
      createPaper: function () {
        if (this.checkForm()) {
          var self = this;
          self.paper.endTime = self.$refs.endTime.value;
          self.paper.userId = ${user.id};
          self.paper.courseId = self.kid;
          if (self.paper.name.indexOf(Hvm.course.name + "-") === -1)
            self.paper.name = Hvm.course.name + "-" + self.paper.name;
          $.post('/course/set/paper/${kid}/create', self.paper, function (data) {
            if (data.success) {
              self.paper = data.payload;
              self.papers.unshift(self.paper);
              if (self.papers.length > self.page.limit) self.getPages();
            }
          });
        }
      },
      getPages: function () {
        var self = this;
        $.post('/course/paper/api/${kid}/page', {page: this.page.pageNum}, function (data) {
          if (data.success) {
            self.papers = data.payload.rows;
            self.page.limit = data.payload.limit;
            self.page.pageNum = data.payload.pageNum;
            self.page.totalPages = data.payload.totalPages;
          }
        });
      },
      checkForm: function () {
        var paper = this.paper;
        var nd = new Date().getTime();
        var td = new Date(paper.endTime).getTime();
        if (isEmpty(paper.name)) {
          layer.msg("试卷名不能为空！", {time: 1200});
        } else if (td < nd) {
          layer.msg("结束时间不能在当前时间前面！", {time: 1200});
        } else if (isEmpty(paper.intro)) {
          layer.msg("考试说明不能为空！", {time: 1200});
        } else if (isEmpty(paper.path)) {
          layer.msg("试卷必须上传！", {time: 1200});
        } else return true;
        return false;
      }
    },
    components: {
      'paper-li': {
        props: ['paper', 'index', 'edit_', 'delete_'],
        template: '#paper-li',
        methods: {
          down: function (path) {
            if (path!=null && path.trim()!=='') {
              var tp = '答案';
              if (path.indexOf("t=1")!==-1) tp = '试卷';
              window.open(path+"&name="+this.paper.name+"("+tp+")", '_top');
            } else {
              layer.msg('文件还没有被上传！', {time: 1500, icon: 5});
            }
          }
        },
        filters: {
          sub: function (value) {
            if (value.indexOf(Hvm.course.name) !== -1) {
              return value.substr(value.indexOf("-") + 1);
            }
            return value;
          }
        }
      }
    },
    created: function () {
      this.getPages();
    },
    mounted: function () {
      var self = this;
      self.$refs.upload_paper.onclick = function () {
        self.fileType = 'test_paper';
        self.$refs.file_in.click();
      };
      self.$refs.upload_result.onclick = function () {
        self.fileType = 'test_result';
        self.$refs.file_in.click();
      };
      self.$refs.file_in.onchange = function (e) {
        var inp = e.target;
        var file = inp.files[0];
        uploadFile(file, self.paper.folder, self.fileType, function (data) {
          if (self.fileType === 'test_paper') {
            self.paper.path = data.payload.path;
          } else if (self.fileType === 'test_result') {
            self.paper.result = data.payload.path;
          }
        })
      };
    }
  });

  function uploadFile(file, folder, type, fun) {
    paperVm.progress = 0;
    var fd = new FormData();
    fd.append('file', file);
    fd.append('type', type);
    fd.append('kid', '${kid}');
    fd.append('path', folder);
    if (paperVm.paper.id>0) {
      fd.append('pid', paperVm.paper.id);
      var p = paperVm.paper.path;
      var start = p.indexOf("f=") + 2;
      if (start === 1) {
        start = p.indexOf("/paper/") + 7;
      }
      var name = p.substring(start, p.indexOf(".", start));
      fd.append('name', name);
    }
    var xhr = new XMLHttpRequest();
    xhr.open('post', '/file/t/upload', true);
    xhr.onload = function () {
      var data = JSON.parse(xhr.responseText);
      paperVm.$refs.file_in.value = null;
      fun ? fun(data) : null;
    };
    xhr.upload.onprogress = function (ev) {
      paperVm.progress = parseInt(ev.loaded / ev.total * 100);
    };
    xhr.send(fd);
  }

  ///////////////////////////////////////////
  function getDate(offset) {
    if (offset == null) offset = 0;
    var now = new Date();
    var date = new Date(now.getTime() + 1000 * 3600 * 24 * offset);
    return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
  }

  $('#del').on('click', function () {
    layer.confirm("删除后无法撤回，是否删除", {
      icon: 3,
      title: '提示',
      anim: 0,
      btn: ['删除', '取消']
    }, function (index) {
      layer.close(index)
    }, function () {

    });
  });
  laydate.render({
    elem: '#endTime',
    type: 'date',
    min: 1
  });

  function hideM(tip) {
    if (tip) {
      layer.confirm('退出后未保存的数据将丢失！确定退出？',{icon:5, title:'警告'},function (i) {
        $('#createNotice').modal('hide');
        layer.close(i);
      });
    } else {
      $('#createNotice').modal('hide');
    }
  }

  function openM() {
    $('#createNotice').modal('show');
  }

  $('#createNotice').on('show.bs.modal', function () {
    var et = getDate(7);
    if (paperVm.paper.endTime!=null&&paperVm.paper.endTime!=='') et = paperVm.paper.endTime;
    $('#endTime').val(et);
  }).on('hidden.bs.modal', function () {
    paperVm.paper = {id: 0, path: null, result: null};
    paperVm.$refs.file_in.value = null;
    paperVm.progress = -1;
  });
</script>

#include('/footer.html')